package dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.sun.org.apache.regexp.internal.recompile;

import bean.Album;

import dao.AlbumDao;

public class AlbumDaoImpl extends HibernateDaoSupport implements AlbumDao {

	@Override
	public boolean addAlbum(Album album) {
		this.getSessionFactory().getCurrentSession().save(album);
		return true;
	}

	@Override
	public boolean deleteAlbum(Album album) {
		// TODO Auto-generated method stub
		this.getSessionFactory().getCurrentSession().delete(album);
		return true;
	}

	@Override
	public boolean modifyAlbum(Album album) {
		this.getSessionFactory().getCurrentSession().update(album);
		return true;
	}

	@Override
	public List findAlbumsByUsername(String username) {
		List l = this.getSessionFactory().getCurrentSession()
				.find("from album a where a.user.username='" + username + "'");
		return l;
	}

	@Override
	public List findAlbumsByView(int view) {
		List l = this.getSessionFactory().getCurrentSession()
				.createCriteria(Album.class).add(Restrictions.gt("view", view))
				.list();
		return l;
	}

	@Override
	public List findAlbumsByDate(Date date) {
		// TODO Auto-generated method stub
		List l = this.getSessionFactory().getCurrentSession()
				.createCriteria(Album.class).add(Restrictions.gt("time", date))
				.list();
		return l;
	}

	@Override
	public List findAlbumsByUserid(int id) {
		List l = this.getSessionFactory().getCurrentSession()
				.createCriteria(Album.class)
				.add(Restrictions.eq("user.id", id)).list();
		return l;
	}

	@Override
	public Album findAlbumById(int id) {
		Object o = this.getSessionFactory().getCurrentSession()
				.load(Album.class, id);
		if(o==null)
			return null;
		else
			return (Album) o;
	}

	@Override
	public List findAlbumsByTitle(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List findAlbumsByName(String name) {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().createCriteria(Album.class).add(Restrictions.like("title", "%"+name+"%")).list();
		System.out.println(l.size());
		return l;
	}

	@Override
	public List findRecentAlbums() {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().find("from Album a order by id desc");
		if(l.size()>5)
			return l.subList(0, 5);
		else
			return l;
	}

}
